﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

using XRpgLibrary.ScriptClasses;

namespace XLevelEditor
{
    public partial class FormWireScript : Form
    {
        static Dictionary<string, List<string>> scriptList;
        public static Dictionary<string, List<string>> ScriptList
        {
            get
            {
                //if (scriptList == null)
                {
                    scriptList = new Dictionary<string, List<string>>();
                    PopulateScriptList();
                }

                return scriptList;
            }
        }
        
        public string Event
        {
            get
            {
                return cbEvent.SelectedItem.ToString();
            }
        }

        public string ScriptName
        {
            get
            {
                return cbNamespaces.SelectedItem.ToString() + "." + cbScripts.SelectedItem.ToString();
            }
        }

        public FormWireScript()
        {
            InitializeComponent();
        }

        private void FormWireScript_Load(object sender, EventArgs e)
        {
            cbNamespaces.Items.AddRange(ScriptList.Keys.ToArray<object>());
            cbNamespaces.SelectedIndex = 0;
            cbEvent.SelectedIndex = 0;            
        }

        private static void PopulateScriptList()
        {
            Assembly scriptAssembly = Assembly.GetAssembly(typeof(ScriptContext));
            foreach (Type type in scriptAssembly.GetExportedTypes())
            {
                if (type.Namespace.Contains("XRpgLibrary.Scripts"))
                {
                    if (!scriptList.ContainsKey(type.Namespace))
                        scriptList.Add(type.Namespace, new List<string>());

                    scriptList[type.Namespace].Add(type.Name);
                }
            }
        }

        private void cbNamespaces_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbScripts.Items.Clear();
            cbScripts.Items.AddRange(ScriptList[cbNamespaces.SelectedItem.ToString()].ToArray<object>());
            cbScripts.SelectedIndex = 0;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {        
            DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}
